import React, {useEffect, useRef, useState} from "react";
import {Dropdown, Space} from "antd";
import { DownOutlined } from "@ant-design/icons";
import { Enums, init as csRenderInit, RenderingEngine, imageLoader, metaData } from "@cornerstonejs/core";
import initCornerstoneDICOMImageLoader from "../utils/initCornerstoneDICOMImageLoaderT.js";
import {wadouri} from "@cornerstonejs/dicom-image-loader";
import * as cornerstoneTools from "@cornerstonejs/tools";
import "./index.css";
import axios from "axios";
import {removeAllAnnotations} from "@cornerstonejs/tools/dist/esm/stateManagement/annotation/annotationState"
import dicomParser from "dicom-parser";
import { addButtonToToolbar } from "../utils/addButtonToToolbar.js";
import { saveAs } from "file-saver";
import htmlDocx from "html-docx-js/dist/html-docx";
import request from "../api/request.js"

import { Layout, Button, Input, Slider, Select, List, message, Upload, Spin, Image, Tabs, Form } from "antd";
import { UploadOutlined } from "@ant-design/icons";
import CustomProbeTool from './CustomProbeTool.js'

const { Header, Sider, Content } = Layout;

const {ViewportType, Events} = Enums;

const renderingEngineId = "myRenderingEngine";
const viewportId = "CT_STACK";

const windowWidth = 1500;
const windowCenter = -450;

const lower = windowCenter - windowWidth / 2.0;
const upper = windowCenter + windowWidth / 2.0;

const ctVoiRange = {lower, upper};

const tools = [
    {
        tool: cornerstoneTools.WindowLevelTool,
        name: cornerstoneTools.WindowLevelTool.toolName,
        mouse: cornerstoneTools.Enums.MouseBindings.Primary
    },
    {
        tool: cornerstoneTools.PanTool,
        name: cornerstoneTools.PanTool.toolName,
        mouse: cornerstoneTools.Enums.MouseBindings.Primary
    },
    {
        tool: cornerstoneTools.ZoomTool,
        name: cornerstoneTools.ZoomTool.toolName,
        mouse: cornerstoneTools.Enums.MouseBindings.Primary
    },
    {
        tool: cornerstoneTools.StackScrollMouseWheelTool,
        name: cornerstoneTools.StackScrollMouseWheelTool.toolName
    },
    {
        tool: cornerstoneTools.LengthTool,
        name: cornerstoneTools.LengthTool.toolName,
        mouse: cornerstoneTools.Enums.MouseBindings.Primary
    },
    {
        tool: CustomProbeTool,
        name: CustomProbeTool.toolName,
        // tool: cornerstoneTools.ProbeTool,
        // name: cornerstoneTools.ProbeTool.toolName,
        mouse: cornerstoneTools.Enums.MouseBindings.Primary
    }
];

const wwwcOptions = [
    { windowWidth: 1500, windowCenter: -450 }, // 原始窗
    { windowWidth: 1500, windowCenter: -600 }, // 肺窗
    { windowWidth: 1500, windowCenter: 300 }, // 骨窗
    { windowWidth: 350, windowCenter: 40 }, // 纵隔窗
    { windowWidth: 1700, windowCenter: -500 }, // 肺窗2
    { windowWidth: 400, windowCenter: 40 }, // 腹窗
    { windowWidth: 600, windowCenter: 300 }, // 血管造影
    { windowWidth: 80, windowCenter: 40 }, // 脑窗
  ];

const menuTools = [
    {
        label: "长度测量",
        key: cornerstoneTools.LengthTool.toolName,
    },
    {
        label: "CT值测量",
        key: cornerstoneTools.ProbeTool.toolName,
    }
];

const columnNames = ["腺癌", "鳞癌", "良性其他", "小细胞癌"];

let docImageData = {};

/**
 * demo按照file加载的模式
 */
function StackImages() {
    let isScrolling = false;

    let toolGroup = useRef(null);

    let pointRectShowStateRef = useRef("hidden");

    let docImageViewport = useRef(null);

    const [messageApi, contextHolder] = message.useMessage();

    const [loading, setLoading] = React.useState(false);

    // 被点击的list变颜色
    let [clickedIndex, setClickedIndex] = useState(null);
    let txtRef = useRef(null);
    let sortDataRef = useRef(null);
    let maxColumnsRef = useRef([]);
    let csvFileRef = useRef([]);
    let accessionNumberREF = useRef("");
    let [ctNumber, setCtNumber] = useState("");
    let [titleName, setTitleName] = useState("");
    let selectedIndex = useRef([]);
    let imageIdref = useRef([]);
    let [dicom, setDicom] = useState([]);
    let [viewport, setViewport] = useState(null);
    let [dicomBasicInfo, setDicomBasicInfo] = useState(null);
    let [currentImageIdIndex, setCurrentImageIdIndex] = useState(0);
    let [currentCsvIndex, setCurrentCsvIndex] = useState(-1);
    let [pointRectShowState, setPointRectShowState] = useState("hidden");   // show hidden

    useEffect(() => {
        const content = document.getElementById("content");
        if (!content.children || (content.children.length === 0)) {
            setup();
        }
    }, []);

    useEffect(() => {
        pointRectShowStateRef.current = pointRectShowState;
    }, [pointRectShowState]);

    const setup = async () => {
        // dom
        const content = document.getElementById("content");
        const element = document.createElement("div");
        element.id = "cornerstone-element";
        element.style.width = "100%";
        element.style.height = "100%";
        content.appendChild(element);

        // init
        initCornerstoneDICOMImageLoader();
        await csRenderInit({
            gpuTier: {
                tier: 0
            }
        });
        const renderingEngine = new RenderingEngine(renderingEngineId);
        const viewportInput = {
            viewportId,
            type: ViewportType.STACK,
            element
        };
        renderingEngine.enableElement(viewportInput);
        setViewport(renderingEngine.getViewport(viewportId));

        initTools();
    };

    

    const loadImageStack = async (imageIds) => {
        console.log("loadImageStack before", imageIds);
        // stack render
        await viewport.setStack(imageIds);
        console.log("loadImageStack after", imageIds);
        viewport.setProperties({voiRange: ctVoiRange});
        viewport.resize();
        viewport.render();

        // load dicom info
        const image = viewport.csImage;
        const patientName = image.data.string("x00100010") || "N/A";
        const patientID = image.data.string("x00100020") || "N/A";
        const patientAge = image.data.string("x00101010") || "N/A";
        const patientSex = image.data.string("x00100040") || "N/A";
        const patientStudyDate = image.data.string("x00080020") || "N/A";
        setDicomBasicInfo({patientName, patientID, patientAge, patientSex, patientStudyDate});
        // add event listener
        viewport.element.addEventListener(Events.IMAGE_RENDERED, onImageRender);
        window.addEventListener("resize", handleResize);
    };

    const handleResize = () => {
        viewport.resize();
        viewport.render();
    };

    const parseTXT = (contents) => {
        const lines = contents.split("\n");
        const spacingLine = lines[0];
        const spacing = spacingLine.match(/Spacing=\(([^)]+)\)/)?.[1].split(",").map(Number) || [];
      
        const parsedData = {
          spacing: spacing,
          slices: [],
        };
      
        for (let i = 2; i < lines.length; i++) {
          const line = lines[i].trim();
          if (!line) {
            continue;
          }
          const [slice, leftX, leftY, rightX, rightY, centerPoint, width, height] = line.split(/\s+/);
          const [centerX, centerY] = centerPoint.replace(/[()]/g, "").split(",").map(Number);
      
          parsedData.slices.push({
            slice: Number(slice),
            leftX: Number(leftX),
            leftY: Number(leftY),
            rightX: Number(rightX),
            rightY: Number(rightY),
            centerPoint: { x: centerX, y: centerY },
            width: Number(width),
            height: Number(height),
          });
        }
      
        return parsedData;
      };
      
    const uploadTxt = async () => {
        // const text = `Spacing=(0.705078, 0.705078, 0.625)
        // Slice		Left X		Left Y		Right X		Right Y		Center Point		Width(mm)		Height(mm)
        // 0			125				366				142				382				(133,374)				11.99				11.28
        // 0			306				363				319				376				(312,369)				9.17				9.17
        // 0			135				339				169				374				(152,356)				23.97				24.68
        // 1			156				331				168				343				(162,337)				8.46				8.46
        // `;
        // const txt = parseTXT(text);
        // txtRef.current = txt;
        // console.log('txtRef', txtRef.current);
        // // 从大到小排列
        // const sortedSlices = txt.slices.slice().sort((a, b) => a.slice - b.slice);
        // sortDataRef.current = sortedSlices
        // console.log('sortDataRef', sortDataRef.current);
        try {
            await request({
                url: "/get_txt",
                method: "GET"
              }).then((res) => {
                const text = res;
                const txt = parseTXT(text);
                console.log("txt", txt);
                txtRef.current = txt;
                // 从大到小排列
                const sortedSlices = txt.slices.slice().sort((a, b) => a.slice - b.slice);
                sortDataRef.current = sortedSlices;
            });
        } catch (error) {
            message.error("结节信息请求发生错误①", error);
        }
    };

    const uploadCsv = async () => {
        // const data = [
        //     [
        //         "",
        //         "0",
        //         "1",
        //         "2",
        //         "3"
        //     ],
        //     [
        //         "0",
        //         "1.6814969e-05",
        //         "0.43286294",
        //         "0.02283739",
        //         "0.0020410111"
        //     ],
        //     [
        //         "1",
        //         "4.036417e-09",
        //         "1.7340311e-05",
        //         "0.99996483",
        //         "1.7683313e-05"
        //     ],
        //     [
        //         "2",
        //         "1.4228116e-08",
        //         "0.9999912",
        //         "8.869274e-06",
        //         "4.5786347e-08"
        //     ],
        //     [
        //         "3",
        //         "2.321017e-05",
        //         "0.01246444",
        //         "0.0057162126",
        //         "0.0001157459"
        //     ]
        // ];
        // const trimmedData = data.slice(1).map(row => row.slice(1));
        // // const trimmedData = data.slice(1, -1).map(row => row.slice(1));
        //     const formattedData = trimmedData.map(row => 
        //         row.map(value => {
        //             const num = Number(value);
        //             return num.toFixed(10); // 使用 toFixed(10) 格式化为 10 位小数
        //         })
        //     );
        //     csvFileRef.current = formattedData;
        //     console.log("csv", formattedData);
        //     console.log("csvFileRef.current", csvFileRef.current);
        //     const maxCols = trimmedData.map(row => {
        //         let maxVal = Number.MIN_VALUE;
        //         let maxIndex = -1;
        //         row.forEach((value, index) => {
        //         const floatValue = parseFloat(value);
        //         if (floatValue > maxVal) {
        //             maxVal = floatValue;
        //             maxIndex = index;
        //         }
        //         });
        //         return columnNames[maxIndex];
        //     });
        //     console.log("maxCols", maxCols);
        //     maxColumnsRef.current = maxCols;
        //     console.log("maxColumnsRef", maxColumnsRef.current);
        try {
            await request({
                url: "/get_csv",
                method: "GET"
              }).then((res) => {
                console.log("csv", res);
                const data = res;
                // const trimmedData = data.slice(1, -1).map(row => row.slice(1));
                const trimmedData = data.slice(1).map(row => row.slice(1));
                const formattedData = trimmedData.map(row => 
                    row.map(value => {
                        const num = Number(value);
                        return num.toFixed(10); // 使用 toFixed(10) 格式化为 10 位小数
                    })
                );
                csvFileRef.current = formattedData;
                console.log("csv", formattedData);
                console.log("csvFileRef.current", csvFileRef.current);
                const maxCols = trimmedData.map(row => {
                    let maxVal = Number.MIN_VALUE;
                    let maxIndex = -1;
                    row.forEach((value, index) => {
                    const floatValue = parseFloat(value);
                    if (floatValue > maxVal) {
                        maxVal = floatValue;
                        maxIndex = index;
                    }
                    });
                    return columnNames[maxIndex];
                });
                console.log("maxCols", maxCols);
                maxColumnsRef.current = maxCols;
                console.log("maxColumnsRef", maxColumnsRef.current);
            });
        } catch (error) {
            message.error("结节信息请求发生错误②", error);
        }
    }

    const onImageRender = () => {
        setCurrentImageIdIndex(viewport.currentImageIdIndex);
        if (pointRectShowStateRef.current === "show") {
            drawRect();
        }
        isScrolling = false;
    };

    const initTools = () => {
        tools.forEach((v) => {
            cornerstoneTools.addTool(v.tool);
        })
        toolGroup.current = cornerstoneTools.ToolGroupManager.createToolGroup("myToolGroup");
        tools.forEach((v) => {
            toolGroup.current.addTool(v.name);
        })
        // 左键
        tools.forEach((v) => {
            if (v.mouse) {
                // 包含鼠标事件的工具
                toolGroup.current.setToolActive(v.name, {
                    bindings: [{mouseButton: v.mouse}]
                });
            } else {
                toolGroup.current.setToolActive(v.name);
            }
        })
        toolGroup.current.addViewport(viewportId, renderingEngineId);
    };

    const handleToolMenuClick = (info) => {
        tools.forEach((v) => {
            if (v.mouse && (v.mouse === cornerstoneTools.Enums.MouseBindings.Primary)) {
                toolGroup.current.setToolPassive(v.name);
            }
        })
        toolGroup.current.setToolActive(info.key, {
            bindings: [{mouseButton: cornerstoneTools.Enums.MouseBindings.Primary}]
        });
    };

    const toggleShowRect = () => {
        const next = pointRectShowState === "show" ? "hidden" : "show";
        setPointRectShowState(next);
        if (next === "show") {
            drawRect();
        } else {
            viewport.render();
        }
    };

    const drawRect = () => {
        if (!viewport) return;
        const context = viewport.canvas.getContext("2d");
        const slices = sortDataRef.current;
        for(let i = 0; i < slices.length; i ++) {
            const item = slices[i];
            const slice = item.slice;
            const leftX = item.leftX;
            const leftY = item.leftY;
            const rightX = item.rightX;
            const rightY = item.rightY;
            if (slice === viewport.currentImageIdIndex) {
                context.strokeStyle = "rgba(41, 198, 33, 1)";
                context.fillStyle = "rgba(41, 198, 33, 1)";
                // 计算矩形的宽度和高度
                const width = Math.abs(leftX - rightX);
                const height = Math.abs(leftY - rightY);
                context.strokeRect(leftX, leftY, width, height)
                // context.textAlign = "left";
                // context.font = "15px serif";
                // context.fillText(maxColumnsRef.current[i], rightX + 3, rightY);
            }
        }
    };

    const handleWWWC = (value) => {
        // wwwcOptions
        const lower = wwwcOptions[value].windowCenter - wwwcOptions[value].windowWidth / 2.0;
        const upper = wwwcOptions[value].windowCenter + wwwcOptions[value].windowWidth / 2.0;

        const ctVoiRange = {lower, upper};
        viewport.setProperties({voiRange: ctVoiRange})
        viewport.render();
    }

    
    const goToPage = (targetIndex) => {
        // Ensure that targetIndex is within valid range
        if (targetIndex < 0 || targetIndex >= viewport.imageIds.length) {
            return;
        }
        if (!viewport) return ;
        if (isScrolling) return ;
        if (targetIndex === viewport.currentImageIdIndex) return;
        isScrolling = true;
        const currentIndex = viewport.currentImageIdIndex;
        const delta = targetIndex - currentIndex;
        // 创建滚动选项对象
        const options = {
            delta: delta, // 滚动的增量
        };
        try {
            cornerstoneTools.utilities.scroll(viewport, options);
        } catch (error) {
            console.error("Error while scrolling:", error);
        }
    }

    const onClickpdf = async () => {

        console.log("sortData", sortDataRef.current);
        console.log("csvFile", csvFileRef.current);
        // 创建包含图像的 HTML 字符串
        let htmlString = `
        <!DOCTYPE html>
        <html>
        <head>
            <style>
            body {
                font-family: Arial, sans-serif;
            }
            h1 {
                font-size: 30px;
                text-align: center;
            }
            h3 {
                text-align: center;
            }
            hr {
                border: 1px solid #000;
            }
            .patient-info {
                font-size: 14px;
            }
              .hr-dashed-fixed {
                border: 0;
                padding-top: 1px;
                /* for IE浏览器 */
                background: repeating-linear-gradient(to right, #a2a9b6 0px, #a2a9b6 4px, transparent 0px, transparent 10px);
                /* for 现代浏览器 */
                background: repeating-linear-gradient(to right, #a2a9b6 0 var(--dashed-filled, 4px), transparent 0 calc(var(--dashed-filled, 4px) + var(--dashed-open, 6px)));//传入变量来定义疏密
            }
            </style>
        </head>
        <body>
            <h1>肺部CT报告</h1>
            <hr class="hr-dashed-fixed" style="--dashed-filled: 8px; --dashed-open: 4px;"/>
            <div class="patient-info">
            <p>ID: ${dicomBasicInfo.patientID}</p>
            <p>姓名: ${dicomBasicInfo.patientName}</p>
            <p>年龄: ${dicomBasicInfo.patientAge}</p>
            <p>性别: ${dicomBasicInfo.patientSex}</p>
            <p>检查日期: ${dicomBasicInfo.patientStudyDate}</p>
            </div>
          <hr class="hr-dashed-fixed" style="--dashed-filled: 8px; --dashed-open: 4px;"/>
          <h3>
            报告详情
          </h3>
          `

        // 加入图片
        const docImages = await getDocImages();
        console.log("docImages", docImages);
        
        
        // Create a map to store the corresponding sortData and maxColumns for each image
        const imageDataMap = new Map();

        for (let i = 0; i < sortDataRef.current.length; i++) {
            const item = sortDataRef.current[i];
            const imageId = item.slice; // 假设 sortData 中有 imageId 属性与 docImages 对应
            let probabilitiesString = "";

            if (!imageDataMap.has(imageId)) {
                imageDataMap.set(imageId, []);
            }
            const selectedData = csvFileRef.current[i];
            for (let j = 0; j < selectedData.length; j++) {
                probabilitiesString += `${columnNames[j]}: ${selectedData[j]}<br/>`;
            }
            
            imageDataMap.get(imageId).push({
                description: maxColumnsRef.current[i],
                width: item.width,
                height: item.height,
                probabilities: probabilitiesString
            });
        }
        console.log("imageDataMap", imageDataMap);

        for (let i = 0; i < docImages.length; i++) {
            const imageItem = docImages[i];
            // const len = viewport.imageIds.length
            const imageId = imageItem.slice; // 假设 docImages 中有 id 属性
            const imageData = imageDataMap.get(imageId) || [];
            console.log("i", i, imageItem, imageData);
        
            htmlString += `<img src="${imageItem.image}" alt="CT Image"/>`;
        
            for (let j = 0; j < imageData.length; j++) {
                const data = imageData[j];
                htmlString += `
                    <p>描述：${data.description} ${data.width}mm × ${data.height}mm
                    <br />
                    其他概率：${data.probabilities}
                    </p>
                    <br/>
                `;
            }
        }

        // 结尾
        htmlString += `
        <h4>影像所见：</h4>
        <br/>
        <h4>防范建议：</h4>
        <br/>
        </body>
        </html>
        `;
        // 使用 html-docx-js 将 HTML 字符串转换为 DOCX
        const blob = htmlDocx.asBlob(htmlString);
        saveAs(blob, `${dicomBasicInfo.patientID}肺部CT报告.docx`);
        
    }

    const onDocImageRender = () => {
        const context = docImageViewport.value.canvas.getContext("2d");
        const page = docImageViewport.value.currentImageIdIndex;
        for (let i = 0; i < sortDataRef.current.length; i++) {
            if (page === sortDataRef.current[i].slice)
            {
                const { leftX, leftY, rightX, rightY } = sortDataRef.current[i];
                context.strokeStyle = "rgba(41, 198, 33, 1)";
                context.fillStyle = "rgba(41, 198, 33, 1)";
                const width = Math.abs(leftX - rightX);
                const height = Math.abs(leftY - rightY);
                context.strokeRect(leftX, leftY, width, height);
            }
        }
        const data = docImageViewport.value.canvas.toDataURL("image/png");
        docImageData.resolve(data);
    }

    const getOneDocImage = (item) => {
        return new Promise(async (resolve, reject) => {
            docImageData = {
                resolve,
                data: null
            };
            docImageViewport.value.setImageIdIndex(item.slice);
            await drawRectSingle(item);
        })
    }

    const drawRectSingle = (item) => {
        const context = docImageViewport.value.canvas.getContext("2d");
        const slice = item.slice;
        const leftX = item.leftX;
        const leftY = item.leftY;
        const rightX = item.rightX;
        const rightY = item.rightY;
        if (slice === viewport.currentImageIdIndex) {
            context.strokeStyle = "rgba(41, 198, 33, 1)";
            context.fillStyle = "rgba(41, 198, 33, 1)";
            // 计算矩形的宽度和高度
            const width = Math.abs(leftX - rightX);
            const height = Math.abs(leftY - rightY);
            context.strokeRect(leftX, leftY, width, height)
            // context.textAlign = "left";
            // context.font = "15px serif";
            // context.fillText(maxColumnsRef.current[item.index], rightX + 3, rightY);
        }
    }

    const getDocImages = () => {
        console.log("getDocImages");

        return new Promise(async (resolve, reject) => {
            // const curFiles = dicom;
            // const imageIds = [];
            // for (let i = 0; i < curFiles.length; i++) {
            //     imageIds[i] = wadouri.fileManager.add(curFiles[i]);
            // }

            const element = document.createElement("div");
            element.id = "cornerstone-element-doc";
            element.style.width = "350px";
            element.style.height = "350px";
            element.style.visible = "hidden";
            document.body.appendChild(element);
            const viewportId = "CT_Stack_doc";
            const renderingEngine = new RenderingEngine("RenderingEngineDoc");
            const viewportInput = {
                viewportId,
                type: ViewportType.STACK,
                element
            };
            renderingEngine.enableElement(viewportInput);
            docImageViewport.value = renderingEngine.getViewport(viewportId);
            docImageViewport.value.element.addEventListener(Events.IMAGE_RENDERED, onDocImageRender);
            // docImageViewport.value.setStack(imageIds);
            docImageViewport.value.setStack(imageIdref.current);
            docImageViewport.value.setProperties({voiRange: ctVoiRange});

            const slices = sortDataRef.current;
            const result = [];
            const processedSlices = new Set();  // 用于跟踪已处理的slice页码
            for (let i = 0; i < slices.length; i++) {
                const item = slices[i];
                // 如果当前slice页码已处理，则跳过
                if (processedSlices.has(item.slice)) {
                    continue;
                }
                const image = await getOneDocImage(item);
                result.push({
                    index: i,
                    slice: item.slice,
                    image
                })
                // 标记当前slice页码为已处理
                processedSlices.add(item.slice);
            }
            docImageViewport.value.element.removeEventListener(Events.IMAGE_RENDERED, onDocImageRender);
            document.body.removeChild(element);
            resolve(result);
        })
    }

    const handleListItemClick = (item, index) => {
        selectedIndex.current = index;
        setCurrentCsvIndex(index);
        goToPage(item.slice)
    }
    
      const renderReportContent = () => {
        if (!csvFileRef.current) {
            return ;
        }
        let i = currentCsvIndex;
        if (i === -1) {
            return ;
        }
        const selectedData = csvFileRef.current[currentCsvIndex];

        return (
            <div>
                <p>描述：{maxColumnsRef.current[i]} {sortDataRef.current[i].width}mm × {sortDataRef.current[i].height}mm
                <br />
                其他概率：
                {
                selectedData.map((value, i) => (
                    <div key={i}>{columnNames[i]}: {value}</div>
                ))}
                </p>
                {/* 其他内容 */}
            </div>
        );
    };

    const handleReset = () => {
        viewport.setProperties({voiRange: ctVoiRange});
        viewport.resetCamera();
        removeAllAnnotations();
        viewport.render();
    };

    const queryAndRetrieve = async (accessionNumber) => {
        const requestData = {
            accessionNumber: accessionNumber,
          };
          await axios.post("/api/queryAndRetrieve", requestData, {
            headers: {
              "Content-Type": "application/json",
            }
          });
    }

    const downloadDicom = async (accessionNumber) => {
        const url = `/api/downloadDicom`
          const params = {
            accessionNumber: accessionNumber,
            destinationPath: "/data/test/data/origin/2654624/DICOM/"
          }
        //   await axios.get(url, {params});
          await axios.get(url, {params}).then(res => {
            console.log(res.data);
            setTitleName(res.data);
          });
    }


    const handleSubmit = async (values) => {
        let accessionNumber = values.ctNumber
        accessionNumberREF.current = accessionNumber
        setLoading(true);
        await queryAndRetrieve(accessionNumber);
        await downloadDicom(accessionNumber);
        await getFile()
        
        console.log(accessionNumber);
          
          //从后端请求中获取到studyUID, seriesUID, ObjectUID
          await request({
            url: "/dicom-data",
            method: "GET",
            params: {
                accessionNumber: accessionNumber,
            }
          }).then(async (res) => {
            console.log("/dicom-data", res);
            // let studyUID = "1.2.840.113619.2.416.73414255781898273075982228061966743997";
            // let seriesUID = "1.2.840.113619.2.416.298453895580223092838460484400024009729";
            // let instanceUIDs = ["1.2.840.113619.2.416.2140504919496027131104088923854012098.1","1.2.840.113619.2.416.2140504919496027131104088923854012098.11"];
            let studyUID = res.studies;
            let seriesUID = res.series;
            let instanceUIDs = res.instances;

            // dicom文件先排序，再请求显示
            // instanceUIDs.sort();
            
            let imageIdUrls = [];
            // 创建一个Promise数组来处理所有的异步操作
            instanceUIDs.map(async instance => {
                // const url = `http://localhost:8042/wado?requestType=WADO&studyUID=${studyUID}&seriesUID=${seriesUID}&objectUID=${instance}&contentType=application/dicom`
                const url = `http://10.1.209.4:8042/wado?requestType=WADO&studyUID=${studyUID}&seriesUID=${seriesUID}&objectUID=${instance}&contentType=application/dicom`
                // const url =  `http://39.105.150.149:8042/wado?requestType=WADO&studyUID=${studyUID}&seriesUID=${seriesUID}&objectUID=${instance}&contentType=application/dicom`;
                const encodeUrl = encodeURIComponent(url)
                const imageUrl = `wadouri:http://10.1.209.1:25006/api/downloadsigle?url=${encodeUrl}`;
                // const imageUrl = `wadouri:http://10.1.209.2:25006/api/downloadsigle?url=${encodeUrl}`;
                // const imageUrl = `wadouri:http://10.1.209.4:5006/api/downloadsigle?url=${encodeUrl}`;
                // const imageUrl = `wadouri:http://localhost:3000/api/downloadsigle?url=${encodeUrl}`;
                imageIdUrls.push(imageUrl);
                });
                setDicom(imageIdUrls);
                loadImageStack(imageIdUrls);
                imageIdref.current = imageIdUrls;
            })
            setLoading(false);
      };

      const getFile = async () => {
        const response1 = await request.post("/execute", {
            "script1_path": "/workspace/run_1.sh",
        }); 
        const response2 = await request.post("/execute2", {
            "script2_path": "/workspace/pythonProject/test/run_2.sh"
        });
        if (response1.error) {
            message.warning(response1.error);
        } 
        else if(response2.error){
            message.warning(response2.error);
        }
        else {
            await uploadTxt();
            await uploadCsv();
            message.success("诊断成功。");
        }
      }
    

    const layoutStyle = {
        borderRadius: 0,
        overflow: "hidden",
        width: "100%",
        maxWidth: "100%",
        height: "100vh",
      };
    const headerStyle = {
        textAlign: "center",
        color: "#fff",
        height: "10vh",
        minHeight: "185px",
        maxHeight: "auto",
        position: "relative",
        backgroundColor: "#031c4a",
        // backgroundColor: "#f9f7f7",
      };
    const contentStyle = {
        textAlign: "center",
        minHeight: 120,
        lineHeight: "90%",
        color: "#fff",
        width: "100%",
      };
    const siderStyle = {
        textAlign: "left",
        backgroundColor: "#090b28",
        position: "relative",
      };
    const sliderTopStyle = {
        height: "65%",
        overflow: "auto",
        color: "#808080",
    };
    const sliderBottomStyle = {
        // textAlign: "right",
        minHeight: "86px",
        height: "35%",
        // backgroundColor: "#0958d9",
        overflow: "auto",
        color: "#e1e8f5"
    };

    const buttonStyle = {
        position: "absolute",
        right: "10px",
        bottom: "10px",
    };

    return (
        <Spin spinning={loading} tip="正在诊断，请等待" wrapperClassName="spin-overlay">
        {contextHolder}
        <Layout style={layoutStyle}>
            <Header style={headerStyle}>
            <h1 className={"title-top"}>胸 部 CT 肺 结 节 诊 断 系 统</h1>
                <div className={"logo-left-top"}>
                    <Image src="zghydx.png"></Image>
                </div>
                <div className={"center-tab"}>
                {/*file upload*/}
                <Tabs defaultActiveKey="1"
                centered className={"custom-tab"} tabBarStyle={{ borderBottom: "unset", color: "white" }}
                    items={[{
                        label: `上传文件`,
                        key: "1",
                        children: (    
                        <div>
                        {/*tools*/}
                        <Form onFinish={handleSubmit} layout="inline">
                            <Form.Item
                            label={<span className="custom-label">CT号</span>}
                            name="ctNumber"
                            rules={[{ required: true, message: "请输入CT号" }]}
                            >
                            <Input
                                value={ctNumber}
                                onChange={(e) => setCtNumber(e.target.value)}
                            />
                            </Form.Item>

                            <Form.Item>
                            <Button htmlType="submit">
                                提交
                            </Button>
                            </Form.Item>
                        </Form>
                        <p className="title-name">{titleName}</p>
                        </div>
                        
                    ),
                      }, {
                        label: `操作`,
                        key: "2",
                        children: (<div>
                            <Button onClick={() => {
                                handleToolMenuClick({key: cornerstoneTools.PanTool.toolName})
                            }} style={{marginRight: "5px"}}>
                                平移
                            </Button>
                            <Button onClick={() => {
                                handleToolMenuClick({key: cornerstoneTools.ZoomTool.toolName})
                            }} style={{marginRight: "5px"}}>
                                缩放
                            </Button>
                            <Select
                                defaultValue={0}
                                style={{ width: 220, marginRight: "5px" }}
                                onChange={handleWWWC}
                                options={[
                                    { value: 0, label: "原始窗(WW:1500, WL:-450)" },
                                    { value: 1, label: "肺窗(WW:1500, WL:-600)" },
                                    { value: 2, label: "骨窗(WW:1500, WL:300)" },
                                    { value: 3, label: "纵隔窗(WW:350, WL:40)"},
                                    { value: 4, label: "肺窗2(WW:1700, WL:-500)"},
                                    { value: 5, label: "腹窗(WW:400, WL:40)"},
                                    { value: 6, label: "血管(WW:600, WL:300)"},
                                    { value: 7, label: "脑窗(WW:80, WL:40)"},
                                ]}
                                />
            
                            <Button onClick={() => {
                                handleToolMenuClick({key: cornerstoneTools.WindowLevelTool.toolName})
                            }} style={{marginRight: "5px"}}>
                                自定义窗宽窗位
                            </Button>
                            <Button onClick={toggleShowRect} style={{marginRight: "5px"}}>
                                {pointRectShowState === "show" ? "隐藏肺结节" : "展示肺结节"}
                            </Button>
                            <Button onClick={handleReset} style={{marginRight: "5px"}}>恢复初始样式</Button>
                            <Button onClick={addButtonToToolbar} style={{marginRight: "5px"}}>删除标记</Button>
                            <Dropdown menu={{items: menuTools, onClick: handleToolMenuClick}} style={{marginRight: "5px"}}>
                                <a onClick={e => e.preventDefault()}>
                                    <Space>
                                        测量工具
                                        <DownOutlined />
                                    </Space>
                                </a>
                            </Dropdown>
                        </div>),
                      }]}
                    ></Tabs>
            </div>
                
            
            
            <div className={"logo-right-top"}>
                <Image src="wfsrmyy.png"></Image>
            </div>
            </Header>
            
            <Layout>
                <Content style={contentStyle}>
                <div style={{width: "100%", height: "100%",}}>
                {/*viewport*/}
                <div className={"dicom-viewport-wrapper"}>
                    <div className={"dicom-viewport"} id="content" style={{width: "100%", height: "100%"}}
                        onContextMenu={event => {
                            event.preventDefault();
                        }}
                        onMouseDown={(event) => {
                            event.preventDefault();
                        }}
                    />
                    <div>
                        {
                            dicomBasicInfo &&
                            <div className={"dicom-viewport-overlay-right-top"}>
                                <p>潍坊市人民医院</p>
                                <p>ID:{dicomBasicInfo.patientID}</p>
                                <p>{dicomBasicInfo.patientName}</p>
                                <p>{dicomBasicInfo.patientAge}/{dicomBasicInfo.patientSex}</p>
                                <p>{dicomBasicInfo.patientStudyDate}</p>
                            </div>
                        }
                        <div className={"dicom-viewport-overlay-right-bottom"}>
                            {(currentImageIdIndex + 1) || 1} / {(viewport && viewport.imageIds.length) || 1}
                        </div>
                        <div className={"dicom-viewport-overlay-left-bottom"}>
                            *该系统诊断结果仅供参考
                        </div>
                        <div className={'dicom-slider-right'}>
                            <Slider vertical reverse className={'dicom-slider'} min={0} max = {(viewport && (viewport.imageIds.length - 1)) || 1} tooltip={{ open: false }} value={currentImageIdIndex} 
                            onChange={goToPage} />
                        </div>
                    </div>
                    {/* <div>
                            <Slider vertical reverse className={"dicom-slider"} min={0} max = {(viewport && (viewport.imageIds.length - 1)) || 1} tooltip={{ open: false }} value={currentImageIdIndex} 
                            onChange={goToPage} />
                        </div> */}
                </div>

            </div>
                </Content>
                
                <Sider width="25%" style={siderStyle}>
                    <div style={sliderTopStyle}>
                        {sortDataRef.current && maxColumnsRef.current && viewport.imageIds.length && <List
                                itemLayout="horizontal"
                                dataSource={sortDataRef.current}
                                renderItem={(item, index) => (
                                <List.Item onClick={() => handleListItemClick(item, index)} style={{'margin-left': '20px'}}>
                                    <List.Item.Meta
                                    description={(
                                    <span className="custom-meta-description" style={{'color': index === selectedIndex.current ? '#891313':'#e1e8f5'}}
                                    >
                                    {index + 1}  第{item.slice + 1}页 {item.width}mm × {item.height}mm
                                  </span>
                                  )}
                                    />
                                </List.Item>
                                )}
                            />
                        }
                    </div>
                    <hr className={"hr-twill"} />
                    <div style={sliderBottomStyle}>
                        {sortDataRef.current && maxColumnsRef.current && viewport.imageIds.length && 
                        <div style={{ marginLeft: "20px" }}>
                            {csvFileRef.current.length > 0 && (
                                <div>
                                    {renderReportContent()}
                                </div>
                            )}
                            <Button style={buttonStyle} onClick={() => onClickpdf()}>生成检查报告</Button>
                        </div>
                        }
                    </div>
                </Sider>
            </Layout>
        </Layout>
        </Spin>
    );
}

export default StackImages;
